'use strict';
const path = require("path");
const fs = require("fs");
const tinify = require('tinify');

const key = ""; // 需添加 tinypng 的 KEY

const compressed_assetsDir = path.join(__dirname, "compressed-assets");
const raw_assetsDir = path.join(__dirname, "raw-assets");

function onBuildFinished (options, callback) {
    if (options.buildScriptsOnly) {
        callback();
        return;
    }
    Editor.log('Building options' + JSON.stringify(options)); // 你可以在控制台输出点什么
    const buildResults = options.buildResults;
    // get all textures in build
    const textures = [];
    const assets = buildResults.getAssetUuids();

    const textureType = cc.js._getClassId(cc.Texture2D);

    for (let i = 0; i < assets.length; ++i) {
        const asset = assets[i];
        if (buildResults.getAssetType(asset) === textureType && asset.length === 9) {
            textures.push(buildResults.getNativeAssetPath(asset));
        }
    }
    Editor.log(`All textures in build: ${textures}`);

    const needLoadPaths = [];
    textures.forEach(texturePath => {
        const baseName = path.basename(texturePath);
        const compressedPath = path.join(compressed_assetsDir, baseName);
        // Editor.log(`compressedPath`, compressedPath);
        if (!fs.existsSync(compressedPath)) {
            needLoadPaths.push(texturePath);
        }
        const rawPath = path.join(raw_assetsDir, baseName);
        // Editor.log(`rawPath`, rawPath);
        if (!fs.existsSync(rawPath)) {
            fs.copyFileSync(texturePath, rawPath);
        }
    });
    Editor.log('自动图集图片数量......', textures.length);
    const copyFile = () => {
        textures.forEach(texturePath => {
            const base_name = path.basename(texturePath);
            const compressedPath = path.join(compressed_assetsDir, base_name);
            if (fs.existsSync(compressedPath)) {
                fs.copyFileSync(compressedPath, texturePath);
            } else {
                Editor.error(texturePath, "未压缩...");
            }
        });
        Editor.log('图片全部替换完成......');
        callback();
    };

    if (needLoadPaths.length > 0) {
        Editor.log('开始压缩，数量为：', needLoadPaths.length);
        tinify.key = key;
        // 开始上传压缩
        let compressCompleteCount = 0;
        needLoadPaths.forEach(p => {
            const baseName = path.basename(p);
            const savePath = path.join(compressed_assetsDir, baseName);
            tinify.fromFile(p).toFile(savePath, (err) => {
                compressCompleteCount++;
                if (err) {
                    Editor.log('图片压缩失败', p);
                    Editor.warn('Error:', err);
                } else {
                    // Editor.log(`图片压缩完成数量: `, compressCompleteCount);
                }
                // 全部压完
                if (compressCompleteCount === needLoadPaths.length) {
                    Editor.log(`tinypng 月度压缩次数： `, tinify.compressionCount);
                    copyFile();
                }
            });
        });
    } else {
        Editor.log('待压缩数量为0， 跳过压缩');
        copyFile();
    }
}

module.exports = {
    load () {
        Editor.log('png_compress   load');
        // execute when package loaded
        Editor.Builder.on('build-finished', onBuildFinished);
    },

    unload () {
        Editor.log('png_compress   unload');
        // execute when package unloaded
        Editor.Builder.removeListener('build-finished', onBuildFinished);
    },

    // register your ipc messages here
    messages: {
        'open' () {
            // open entry panel registered in package.json
            Editor.Panel.open('png_compress');
        },
        'say-hello' () {
            Editor.log('Hello World!');
            // send ipc message to panel
            Editor.Ipc.sendToPanel('png_compress', 'png_compress:hello');
        },
        'clicked' () {
            Editor.log('Button clicked!');
        }
    }
};
